let baseUrl = "http://apis.juhe.cn/";

/* POST 请求 */
export function httpPost(url, data, callBack) {
    httpRequest(url, "POST", data, callBack);
}

/* GET 请求 */
export function httpGet(url, callBack) {
    httpRequest(url, "", "GET", callBack);
}

/* 网络请求统一调用 */
function httpRequest(url, data, type, callBack) {
    showProgress(true);
    fetchGetOrPost(url, data, type)
        .then(response => response.json())
        .then(res => requestSuess(callBack, res.result))
        .catch(error => requestError(error));
}

function requestError(error) {
    showProgress(false);
    alert(error);
}

function requestSuess(callBack, result) {
    setTimeout(() => {
        showProgress(false);
        return callBack(result);
    }, 3000);
}

/* 用于判断是get请求还是post 因为默认get请求是没有body参数的 */
function fetchGetOrPost(url, data, type) {
    let fetchData = {
        method: type,
        mode: "cors",
        headers: addHeaders()
    };
    if (type === "POST") {
        fetchData.body = data;
    }
    return fetch(baseUrl + url, fetchData);
}

/* 添加header头部信息 */
function addHeaders() {
    let headers = {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
    };
    return headers;
}

function showProgress(isShow) {
    let loading = document.querySelector("#loadTips");
    if (!loading && !isShow) {
        return;
    }
    if (loading) {
        loading.className = !isShow ? "hide" : "show";
    } else {
        let str =
            '<div class="progress">\n' +
            '                    <div class="show_model"><div class="show_model"><div class="loading"><div class="loading1"></div></div>\n' +
            '                        <div class="show_model_center">\n' +
            '                            <Spin size="large" />\n' +
            "                            <span>正在加载中......</span>\n" +
            "                        </div>\n" +
            "\n" +
            "                    </div>\n" +
            "                </div>";
        var CreateLoad = document.createElement("div");
        CreateLoad.id = "loadTips";
        CreateLoad.className = !isShow ? "wb-fix hide" : "wb-fix";
        CreateLoad.innerHTML = str;
        document.body.appendChild(CreateLoad);
    }
}
